<template>
  <a-modal
    v-model:open="dialogVisible"
    :title="isEdit ? '编辑状态' : '新建状态'"
    :width="640"
    @ok="handleSubmit"
    @cancel="handleCancel"
    :confirm-loading="submitting"
    :mask-closable="false"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      layout="vertical"
    >
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="状态名称" name="name">
            <a-input
              v-model:value="formData.name"
              placeholder="请输入状态名称"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="状态代码" name="code">
            <a-input
              v-model:value="formData.code"
              placeholder="请输入状态代码"
              :disabled="isEdit"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item label="状态描述" name="description">
        <a-textarea
          v-model:value="formData.description"
          placeholder="请输入状态描述"
          :rows="3"
        />
      </a-form-item>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="状态颜色" name="color">
            <div class="color-picker">
              <a-input
                v-model:value="formData.color"
                placeholder="#1890ff"
                style="flex: 1"
              />
              <div class="color-preview" :style="{ backgroundColor: formData.color || '#909399' }"></div>
            </div>
            <div class="color-presets">
              <div
                v-for="color in STATE_COLORS"
                :key="color"
                class="color-preset"
                :class="{ active: formData.color === color }"
                :style="{ backgroundColor: color }"
                @click="formData.color = color"
              ></div>
            </div>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="状态图标" name="icon">
            <div class="icon-selector">
              <a-select
                v-model:value="formData.icon"
                placeholder="选择图标"
                allow-clear
                style="width: 100%"
              >
                <template #suffixIcon>
                  <Icon v-if="formData.icon" :name="formData.icon" :size="16" />
                </template>
                <a-select-option
                  v-for="icon in STATE_ICONS"
                  :key="icon"
                  :value="icon"
                >
                  <div class="icon-option">
                    <Icon :name="icon" :size="16" />
                    <span class="icon-name">{{ icon }}</span>
                  </div>
                </a-select-option>
              </a-select>
              <div class="icon-grid">
                <div
                  v-for="icon in STATE_ICONS"
                  :key="icon"
                  class="icon-item"
                  :class="{ active: formData.icon === icon }"
                  :title="icon"
                  @click="formData.icon = icon"
                >
                  <Icon :name="icon" :size="20" />
                </div>
              </div>
            </div>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="8">
          <a-form-item label="排序顺序" name="sort_order">
            <a-input-number
              v-model:value="formData.sort_order"
              :min="0"
              :max="999"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
        <a-col :span="16">
          <a-form-item label="分组名称" name="group_name">
            <a-input
              v-model:value="formData.group_name"
              placeholder="请输入分组名称"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item label="状态属性">
        <a-space wrap>
          <a-checkbox v-model:checked="formData.is_enabled">启用</a-checkbox>
          <a-checkbox v-model:checked="formData.is_visible">可见</a-checkbox>
          <a-checkbox v-model:checked="formData.is_default">
            <span>设为默认</span>
            <a-tooltip title="新建时默认的状态，一个模块只能有一个默认状态。可以勾选设为默认，也可以取消勾选取消默认。">
              <QuestionCircleOutlined style="margin-left: 4px; color: #8c8c8c;" />
            </a-tooltip>
          </a-checkbox>
          <a-checkbox v-model:checked="formData.is_final">最终</a-checkbox>
          <a-checkbox v-model:checked="formData.is_editable">可编辑</a-checkbox>
        </a-space>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { message } from 'ant-design-vue'
import { QuestionCircleOutlined } from '@ant-design/icons-vue'
import type { FormInstance } from 'ant-design-vue'
import type { StateResponse, StateCreate, StateUpdate } from '@/types/state'
import { STATE_COLORS, STATE_ICONS, ModuleType } from '@/types/state'
import { useStateStore } from '@/stores/state'
import Icon from '@/components/ui/Icon.vue'

// 扩展表单数据类型，包含额外的UI字段
interface ExtendedStateForm extends StateCreate {
  id?: string
  is_final?: boolean
  is_editable?: boolean
  group_name?: string
}

interface Props {
  visible: boolean
  state?: StateResponse | null
  moduleType: ModuleType | string | null
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 使用状态管理store
const stateStore = useStateStore()

const formRef = ref<FormInstance>()
const submitting = ref(false)

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const isEdit = computed(() => !!props.state)

const formData = ref<ExtendedStateForm>({
  name: '',
  code: '',
  description: '',
  color: '#1890ff',
  icon: '',
  module_type: ModuleType.PROJECT, // 默认值，会在 watch 中更新
  is_enabled: true,
  is_visible: true,
  is_default: false,
  is_final: false,
  is_editable: true,
  sort_order: 0,
  group_name: ''
})

const formRules: Record<string, any[]> = {
  name: [
    { required: true, message: '请输入状态名称', trigger: 'blur' },
    { type: 'string', min: 1, max: 50, message: '状态名称长度为1-50个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入状态代码', trigger: 'blur' },
    { type: 'string', pattern: /^[A-Z_][A-Z0-9_]*$/, message: '状态代码只能包含大写字母、数字和下划线，且以字母或下划线开头', trigger: 'blur' }
  ],
  color: [
    { required: true, message: '请选择状态颜色', trigger: 'blur' },
    { type: 'string', pattern: /^#[0-9A-Fa-f]{6}$/, message: '请输入有效的颜色值（如：#1890ff）', trigger: 'blur' }
  ],
  sort_order: [
    { required: true, message: '请输入排序顺序', trigger: 'blur' },
    { type: 'number', min: 0, max: 999, message: '排序顺序必须在0-999之间', trigger: 'blur' }
  ]
}

// 重置表单
const resetForm = () => {
  const defaultModuleType = (props.moduleType && typeof props.moduleType === 'string' 
    ? props.moduleType as ModuleType 
    : (props.moduleType || ModuleType.PROJECT)) as ModuleType
  
  formData.value = {
    name: '',
    code: '',
    description: '',
    color: '#1890ff',
    icon: '',
    module_type: defaultModuleType,
    is_enabled: true,
    is_visible: true,
    is_default: false,
    is_final: false,
    is_editable: true,
    sort_order: 0,
    group_name: ''
  }
}

// 填充表单数据
const fillFormData = (state: StateResponse) => {
  formData.value = {
    id: state.id,
    name: state.name,
    code: state.code,
    description: state.description || '',
    color: state.color || '#1890ff',
    icon: state.icon || '',
    module_type: state.module_type,
    is_enabled: state.is_enabled,
    is_visible: state.is_visible,
    is_default: state.is_default,
    is_final: false, // StateResponse 不包含此字段，使用默认值
    is_editable: true, // StateResponse 不包含此字段，使用默认值
    sort_order: state.sort_order,
    group_name: '' // StateResponse 不包含此字段，使用默认值
  }
}

// 处理提交
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    if (isEdit.value && props.state) {
      // 更新状态
      // 只发送后端支持的字段，移除不支持的字段（is_final, is_editable, group_name）
      const updateData: StateUpdate = {
        name: formData.value.name,
        description: formData.value.description || undefined,
        color: formData.value.color,
        icon: formData.value.icon || undefined,
        is_enabled: formData.value.is_enabled,
        is_visible: formData.value.is_visible,
        is_default: formData.value.is_default,
        sort_order: formData.value.sort_order
      }
      
      await stateStore.updateState(props.state.id, updateData)
      message.success('状态更新成功')
    } else {
      // 创建状态
      const defaultModuleType = (props.moduleType && typeof props.moduleType === 'string' 
        ? props.moduleType as ModuleType 
        : (props.moduleType || ModuleType.PROJECT)) as ModuleType
      
      const createData: StateCreate = {
        name: formData.value.name,
        code: formData.value.code,
        description: formData.value.description,
        color: formData.value.color,
        icon: formData.value.icon,
        module_type: defaultModuleType,
        is_enabled: formData.value.is_enabled,
        is_visible: formData.value.is_visible,
        is_default: formData.value.is_default,
        sort_order: formData.value.sort_order
        // 注意：is_final, is_editable, group_name 不在 StateCreate 中，不发送到后端
      }
      
      await stateStore.createState(createData)
      message.success('状态创建成功')
    }
    
    emit('success')
    dialogVisible.value = false
  } catch (error: any) {
    console.error('提交失败:', error)
    
    // 更详细的错误处理
    let errorMessage = isEdit.value ? '状态更新失败' : '状态创建失败'
    
    if (error?.response?.data?.detail) {
      errorMessage = error.response.data.detail
    } else if (error?.message) {
      errorMessage = error.message
    }
    
    message.error(errorMessage)
  } finally {
    submitting.value = false
  }
}

// 处理取消
const handleCancel = () => {
  dialogVisible.value = false
}

// 监听对话框显示状态
watch(
  () => props.visible,
  (visible) => {
    if (visible) {
      if (props.state) {
        fillFormData(props.state)
      } else {
        resetForm()
      }
    } else {
      formRef.value?.resetFields()
    }
  }
)

// 监听模块类型变化
watch(
  () => props.moduleType,
  (moduleType) => {
    if (moduleType) {
      formData.value.module_type = (typeof moduleType === 'string' 
        ? moduleType as ModuleType 
        : moduleType) as ModuleType
    }
  }
)
</script>

<style scoped>
.color-picker {
  display: flex;
  align-items: center;
  gap: 10px;
}

.color-preview {
  width: 36px;
  height: 36px;
  border-radius: 6px;
  border: 1px solid #d9d9d9;
  flex-shrink: 0;
  transition: transform 0.2s;
}

.color-preview:hover {
  transform: scale(1.05);
}

.color-presets {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 10px;
}

.color-preset {
  width: 28px;
  height: 28px;
  border-radius: 6px;
  cursor: pointer;
  border: 2px solid transparent;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.color-preset:hover {
  transform: scale(1.15);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15);
}

.color-preset.active {
  border-color: #1890ff;
  transform: scale(1.15);
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.icon-selector {
  width: 100%;
}

.icon-option {
  display: flex;
  align-items: center;
  gap: 8px;
}

.icon-name {
  font-size: 14px;
}

.icon-grid {
  display: grid;
  grid-template-columns: repeat(8, 1fr);
  gap: 8px;
  margin-top: 12px;
  padding: 12px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  background: #fafafa;
  max-height: 200px;
  overflow-y: auto;
}

.icon-item {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 36px;
  height: 36px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  background: #fff;
  cursor: pointer;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  color: #595959;
}

.icon-item:hover {
  border-color: #1890ff;
  background: #e6f7ff;
  color: #1890ff;
  transform: scale(1.1);
}

.icon-item.active {
  border-color: #1890ff;
  background: #1890ff;
  color: #fff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.icon-item.active:hover {
  background: #40a9ff;
  border-color: #40a9ff;
}
</style>